from multiprocessing import Process
import random
import datetime
import time

class Worker(Process):
    amount = 100000
    count = 0
    def __init__(self):
        Process.__init__(self)

    def run(self):
        while True:
            w = random.randint(1, 10)
            # w = 1
            if Worker.amount == 0:
                print("票已经抢完了,请下次再来")
                print(f"累计抢票次数:{Worker.count}次")
                break
            if Worker.amount - w < 0:
                continue
            Worker.amount  -= w
            Worker.count += 1
            time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"{time_now}{self.name}已经抢了{w}张,剩余{Worker.amount}张")

"""定义装饰器"""
def pro_zsq(fun):
    def inner(*args,**kwargs):
        print("**********抢票开始**********")
        btime = time.time()
        fun(*args,**kwargs)
        etime = time.time()
        use_time = etime - btime
        print("**********抢票结束**********")
        print(f"累计抢票持续时间:{round(use_time,3)}s")
    return inner

@pro_zsq
def workers_start_work():
    worker1 = Worker()
    worker2 = Worker()
    worker3 = Worker()
    worker1.start()
    worker2.start()
    worker3.start()
    worker1.join()
    worker2.join()
    worker3.join()




if __name__ == "__main__":
    workers_start_work()



